<script lang="ts" setup>
import { message } from 'ant-design-vue'
import { getSearchList } from '~/api/search'
import type { ISearchList } from '~/types/api';

let searchInputValue = ref('') // 输入框内容
let timer = ref<any>() // 定时器
let searchList = ref<ISearchList[]>() // 下拉框列表

// 当输入框输入内容一会后请求接口，显示下拉框
const onSearchInput = function () {
  clearTimeout(timer.value)
  if (searchInputValue.value !== '') {
    timer.value = setTimeout(async () => {
      searchList.value = (await getSearchList({ title: searchInputValue.value })).data
    }, 500)
  }
}

// 下拉框列表数据
let getOptions = computed(
  {
    get: () => {
      return searchList.value?.map((item) => ({ id: item.id, value: item.title })).slice(0, 5)
    },
    set: (val:any) => {
      searchList.value = val
    }
  })

// 搜索后清空输入框内容
const clearInputAndOptions = function () {
  searchInputValue.value = ''
  searchList.value = []
  getOptions.value = []
}

// 搜索执行
const onEnterKeydown = async function () {
  if (searchInputValue.value) {
    clearTimeout(timer.value)
    // 搜索结果页跳转
    await navigateTo({
      path: '/videoListPage',
      query: {
        search: searchInputValue.value
      }
    })
    clearInputAndOptions()
  } else {
    message.info('请输入搜索内容')
  }
}
</script>

<template>
  <div class="search">
    <div absolute flexc z-100 top-5px right-7px @click="(onEnterKeydown())">
      <img src="/images/svg/search.svg" />
    </div>
    <a-auto-complete class="auto-complete" placeholder="请输入搜索内容" v-model:value="searchInputValue" @change="onSearchInput()" :options="getOptions"
      @keydown.enter="onEnterKeydown"  @select="onEnterKeydown()" 
      :defaultActiveFirstOption="false" />
    <!-- <a-auto-complete placeholder="请输入搜索内容" class="w-220px! rounded-119px"/> -->
  </div>
</template>

<style lang='less' scoped>
.search {
  position: relative;
  width: 220px;

  .icon {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    top: 5px;
    right: 7px;
    z-index: 100;
  }

  :deep(.ant-select-selector) {
    border-radius: 119px;
  }

  :deep(.ant-select-selection-search) {
    width: 167px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
}

.auto-complete{
  width: 220px !important;
  border-radius: 119px;
}

</style>